import { addressAPI, addressListAPI } from '@/services/toolService';
import { useCallback, useEffect, useState } from 'react';

/**
 * Address工具的自定义Hook
 * 处理企业地址查询的业务逻辑
 */
export const useAddress = () => {
    // 企业名称
    const [address, setAddress] = useState('');
    // 查询结果
    const [result, setResult] = useState('');
    // 加载状态
    const [isLoading, setIsLoading] = useState(false);
    // 错误信息
    const [error, setError] = useState('');
    // 请求ID，用于轮询结果
    const [requestId, setRequestId] = useState('');
    // 轮询计数器
    const [pollingCount, setPollingCount] = useState(0);
    // 最大轮询次数
    const MAX_POLLING_ATTEMPTS = 30; // 最多轮询30次，约60秒

    // 轮询查询结果
    useEffect(() => {
        if (!requestId) return;

        const timer = setInterval(async () => {
            if (pollingCount >= MAX_POLLING_ATTEMPTS) {
                clearInterval(timer);
                setError('查询超时，请重试');
                setRequestId('');
                setPollingCount(0);
                return;
            }

            try {
                const data = await addressListAPI(requestId);
                if (data?.resultData) {
                    setResult(data.resultData.join('\n'));
                    setRequestId('');
                    setPollingCount(0);
                } else {
                    setPollingCount(prev => prev + 1);
                }
            } catch (e) {
                clearInterval(timer);
                setError(e instanceof Error ? e.message : '查询结果失败');
                setRequestId('');
                setPollingCount(0);
            }
        }, 1000);

        return () => clearInterval(timer);
    }, [requestId, pollingCount]);

    // 提交查询请求
    const handleSubmit = useCallback(async () => {
        if (!address.trim() || isLoading) return;

        setIsLoading(true);
        setError('');
        setResult('');
        setPollingCount(0);

        try {
            const data = await addressAPI(address.trim());
            if (data) {
                setRequestId(data);
            } else {
                throw new Error('未获取到请求ID');
            }
        } catch (err) {
            setError(err instanceof Error ? err.message : "请求错误，请稍后重试");
        } finally {
            setIsLoading(false);
        }
    }, [address, isLoading]);

    // 清除错误信息
    const clearError = useCallback(() => {
        setError('');
    }, []);

    // 判断是否正在处理中
    const isProcessing = isLoading || requestId !== '';

    // 获取进度文本
    const getProgressText = useCallback(() => {
        if (isLoading) return '查询中...';
        if (requestId) return `正在获取结果(${pollingCount})...`;
        return '查找地址';
    }, [isLoading, requestId, pollingCount]);

    return {
        // 状态
        address,
        result,
        error,
        isProcessing,
        // 设置函数
        setAddress,
        setResult,
        // 操作函数
        handleSubmit,
        clearError,
        getProgressText,
    };
};